package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.Userservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * 用户服务实现类
 */
@Service(interfaceClass = Userservice.class)
@Transactional
public class UserServiceImpl implements Userservice {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;


    /**
     * 根据用户名查询用户信息，同时查询其关联的角色信息及对应的权限信息
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);

        if(user == null){
            return null;
        }

        Integer userId = user.getId();
        //依据用户id查询角色
        Set<Role> roles = roleDao.findByUserId(userId);

        for (Role role : roles) {
            Integer roleId = role.getId();
            //依据角色ID查询权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            //使角色关联权限
            role.setPermissions(permissions);
        }
        //使用户关联角色
        user.setRoles(roles);
        return user;
    }
}
